#include "socket.h"

Socket::Socket(QObject *parent)
    : QObject(parent)
{

}

void Socket::timerOut()
{
    qDebug() << "服务端重连中";
    socket->connectToHost("192.168.35.138", 1102);
}

void Socket::onStateChanged(QAbstractSocket::SocketState socketState)
{
    emit signalSendTcpState(socketState);
    switch (socketState) {
    case QAbstractSocket::ConnectedState:
        if (t->isActive()) {
            t->stop();
        }
        break;
    case QAbstractSocket::ClosingState:
    case QAbstractSocket::UnconnectedState:
        if (!t->isActive()) {
            t->start();
        }
        break;
    default:
        break;
    }
}

void Socket::onSocketError(QAbstractSocket::SocketError lse)
{
    Q_UNUSED(lse);
    onStateChanged(QAbstractSocket::UnconnectedState);
}

void Socket::onReadyRead()
{
    qint64 bas = socket->bytesAvailable();

    while (bas > 0) {
        if (socket->isValid() && socket->isReadable()) {
            emit signalSendToThread(socket->readAll());
        }
        else {
            qDebug() << "tcp socket not valid or not readable!";
        }

        bas = socket->bytesAvailable();
    }
}

void Socket::onSendToServer(QByteArray data)
{
    socket->write(data);
}

void Socket::onSocketInit()
{
    socket = new QTcpSocket(this);
    socket->connectToHost("192.168.35.138", 1102);

    t = new QTimer(this);
    t->setInterval(1000);
    connect(t, SIGNAL(timeout()), this, SLOT(timerOut()));


    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
    connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(onStateChanged(QAbstractSocket::SocketState)));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(onSocketError(QAbstractSocket::SocketError)));


#if defined (Q_OS_LINUX)
    settingsVersions = new QSettings(xin::exeName + "Versions", xin::exeName);
#else
    settingsVersions = new QSettings(QString("HKEY_CLASSES_ROOT\\%1Versions").arg("123"), QSettings::NativeFormat);
#endif
}
